package com.example.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.library.entity.Book;

import com.example.library.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@RestController
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") // 替换为你的前端地址
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookMapper bookMapper;

    //根据书籍名称查找书籍
    @GetMapping("/search/name")
    public ResponseEntity<Object> getBooksByName(@RequestParam String name) {
        List<Book> books = bookMapper.selectByName(name);
        if (books == null || books.isEmpty()) {  // 没有查询到
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(books);
    }

    //根据书籍种类查找书籍
    @GetMapping("/search/category")
    public ResponseEntity<Object> getBooksByCategory(@RequestParam Integer category) {
        List<Book> books = bookMapper.selectByCategory(category);
        if (books == null || books.isEmpty()) {  // 没有查询到
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(books);
    }

//    // 根据书籍ID查找书籍
//    @GetMapping("/{id}")
//    public Book getBookById(@PathVariable Long id) {
//        return bookService.getById(id);
//    }

    //添加新书籍
    @PostMapping("/add")
    public Book addBook(@RequestBody Book book){
        bookMapper.insert(book);
        return book;
    }

//    //更新书籍
//    @PutMapping("/update")
//    public Book updateBook(@RequestBody Book book) {
//        bookService.updateById(book);
//        return book;
//    }
//
//    //删除书籍
//    @DeleteMapping("/delete/{id}")
//    public boolean deleteBook(@PathVariable Long id){
//        return bookService.removeById(id);
//

    //查找全部书籍
    @GetMapping("/list")
    public List<Book> books(){
        return bookMapper.select();
    }

}
